package com.example.anni.zhuzhoujia.tianya12345;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by yangshengwen2016 on 2016/6/11.
 * 发布爆料窗口
 */
public class BrokeEstablish extends AppCompatActivity {
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private int i = 0;//看看有多少个图片
    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;

    /*
    * 判断sdcard是否被挂载
    */
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private EditText title;//标题
    private EditText content;//内容
    private EditText summary;//活动地址
    private LinearLayout tupian;//选择图片的线性布局
    private ImageView imageView1;//动态创建的图片
    private LinearLayout add_img;//动态添加图片的线性布局

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.broke_establish);
        tupian = (LinearLayout) findViewById(R.id.tupian);
        add_img = (LinearLayout) findViewById(R.id.add_img);
        tp();//选择图片的方法
        LinearLayout city_return = (LinearLayout) findViewById(R.id.city_return);//返回图片
        city_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView broke_title = (TextView) findViewById(R.id.broke_title);
        broke_title.setText("发布爆料");
        //调用登录接口
        RequestParams params1 = new RequestParams("http://tr.zzapi.gson.cn/api/user/login");
        params1.addBodyParameter("userName", "酷酷猫");
        params1.addBodyParameter("password", "666666");
        x.http().post(params1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {

            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
        title = (EditText) findViewById(R.id.title);//标题
        content = (EditText) findViewById(R.id.content);//内容
        summary = (EditText) findViewById(R.id.summary);//地址
        //设置编辑框焦点情况
        title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    title.setBackgroundResource(R.drawable.edit_background1);
                } else {
                    title.setBackgroundResource(R.drawable.edit_background2);
                }
            }
        });
        content.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    content.setBackgroundResource(R.drawable.edit_background1);
                } else {
                    content.setBackgroundResource(R.drawable.edit_background2);
                }
            }
        });
        summary.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    summary.setBackgroundResource(R.drawable.edit_background1);
                } else {
                    summary.setBackgroundResource(R.drawable.edit_background2);
                }
            }
        });

        ImageView publish = (ImageView) findViewById(R.id.publish);
        //设置发表的单击事件
        publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (title.getText().toString().equals("")) {
                    Toast.makeText(BrokeEstablish.this, "请输入标题！", Toast.LENGTH_LONG).show();
                } else if (content.getText().toString().equals("")) {
                    Toast.makeText(BrokeEstablish.this, "请输入爆料内容！", Toast.LENGTH_LONG).show();
                } else if (summary.getText().toString().equals("")) {
                    Toast.makeText(BrokeEstablish.this, "请输入摘要！", Toast.LENGTH_LONG).show();
                } else {
                    RequestParams params2 = new RequestParams("http://tr.zzapi.gson.cn/api/news/fact/push");
                    params2.setMultipart(true);
                    params2.addBodyParameter("title", title.getText().toString());
                    params2.addBodyParameter("content", content.getText().toString());
                    params2.addBodyParameter("summary", summary.getText().toString());
                    for (int j = 0; j < i; j++) {
                        params2.addBodyParameter("fileItem", new File(Environment.getExternalStorageDirectory().toString() + "/zzj/" + (j + 1) + "imgpng"));
                    }
                    x.http().post(params2, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            JSONObject json1 = JSON.parseObject(s);
                            String success = json1.getString("success");
                            if (success.equals("true")) {
                                if (json1.getString("data") == null) {
                                    Toast.makeText(BrokeEstablish.this, "此新闻已有人爆料！", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(BrokeEstablish.this, "爆料成功！", Toast.LENGTH_LONG).show();
                                    finish();
                                }
                            } else if (success.equals("false")) {
                                Toast.makeText(BrokeEstablish.this, "爆料失败！爆料图片总大小不能超过1MB", Toast.LENGTH_LONG).show();
                            }
                        }

                        @Override
                        public void onError(Throwable throwable, boolean b) {
                            Toast.makeText(BrokeEstablish.this, "发表出错！  出错原因：" + throwable, Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onCancelled(CancelledException e) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                }
            }
        });
    }

    //选择图片的方法
    public void tp() {
        //选择图片的单击事件
        tupian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*//获取布局
                View view = LayoutInflater.from(BrokeEstablish.this).inflate(R.layout.city_establish_img, null);
                //创建Dialog
                final NiftyDialogBuilder dialogBuilder = NiftyDialogBuilder.getInstance(BrokeEstablish.this);
                dialogBuilder
                        .withTitle("请选择图片")  //标题
                        .withIcon(R.mipmap.ysw_img)
                        .withTitleColor("#FFFFFF") //标题颜色
                        .withDividerColor("#11000000") //按钮透明度
                        .withDialogColor("#ff33CCFF") //Dialog整体颜色
                        .isCancelableOnTouchOutside(false)  //点击Dialog以外是否取消
                        .withDuration(500)//动画延迟时间
                        .withEffect(Effectstype.RotateBottom) //动画类型
                        .setCustomView(view, BrokeEstablish.this) //加载内容布局
                        .withButton1Text("取消") //按钮1
                        .setButton1Click(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialogBuilder.dismiss();
                            }
                        })
                        .show();
                Button xc = (Button) view.findViewById(R.id.xc);
                Button pz = (Button) view.findViewById(R.id.pz);
                //从相册获取的按钮
                xc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 激活系统图库，选择一张图片
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image*//*");
                        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                        dialogBuilder.dismiss();
                    }
                });
                //拍照获取
                pz.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 激活相机
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        // 判断存储卡是否可以用，可用进行存储
                        if (hasSdcard()) {
                            tempFile = new File(Environment.getExternalStorageDirectory().toString(), PHOTO_FILE_NAME);
                            // 从文件中创建uri
                            Uri uri = Uri.fromFile(tempFile);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        }
                        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
                        dialogBuilder.dismiss();
                    }
                });*/
                View view = LayoutInflater.from(BrokeEstablish.this).inflate(R.layout.establish_alert_dialog, null);
                TextView xc = (TextView) view.findViewById(R.id.xc);
                TextView pz = (TextView) view.findViewById(R.id.pz);
                TextView qx = (TextView) view.findViewById(R.id.qx);
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(BrokeEstablish.this);
                builder.setView(view);
                final android.app.AlertDialog dialog = builder.create();
                dialog.show();
                // 设置宽高
                dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
                // 设置弹出的动画效果
                dialog.getWindow().setWindowAnimations(R.style.dialog_anim1);
                WindowManager.LayoutParams wlp = dialog.getWindow().getAttributes();
                wlp.gravity = Gravity.BOTTOM;
                dialog.getWindow().setAttributes(wlp);
                xc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 激活系统图库，选择一张图片
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                        dialog.dismiss();
                    }
                });
                pz.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 激活相机
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        // 判断存储卡是否可以用，可用进行存储
                        if (hasSdcard()) {
                            tempFile = new File(Environment.getExternalStorageDirectory().toString(), PHOTO_FILE_NAME);
                            // 从文件中创建uri
                            Uri uri = Uri.fromFile(tempFile);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        }
                        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
                        dialog.dismiss();
                    }
                });
                qx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    //处理图片的方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                Bitmap bm = null;
                //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
                ContentResolver resolver = getContentResolver();
                try {
                    bm = MediaStore.Images.Media.getBitmap(resolver, uri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //动态创建ImageView
                imageView1 = new ImageView(BrokeEstablish.this);
                LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(250, 250);
                lp1.setMargins(5, 5, 5, 5);
                imageView1.setLayoutParams(lp1);
                imageView1.setScaleType(ImageView.ScaleType.CENTER_CROP);
                add_img.addView(imageView1);
                //显得到bitmap图片
                imageView1.setImageBitmap(bm);
                try {
                    i++;
                    saveFile(bm);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            // 从相机返回的数据
            if (hasSdcard()) {
//                crop(Uri.fromFile(tempFile));
                Bitmap bm1 = null;
                //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
                ContentResolver resolver = getContentResolver();
                try {
                    bm1 = MediaStore.Images.Media.getBitmap(resolver, Uri.fromFile(tempFile));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //动态创建ImageView
                imageView1 = new ImageView(BrokeEstablish.this);
                LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(250, 250);
                lp1.setMargins(5, 5, 5, 5);
                imageView1.setLayoutParams(lp1);
                imageView1.setScaleType(ImageView.ScaleType.CENTER_CROP);
                add_img.addView(imageView1);
                //显得到bitmap图片
                imageView1.setImageBitmap(bm1);
                try {
                    i++;
                    saveFile(bm1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else {
                Toast.makeText(BrokeEstablish.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    //保存文件
    public File saveFile(Bitmap bm) throws IOException {
        String path = Environment.getExternalStorageDirectory().toString() + "/zzj/" + i;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        File myImg = new File(path + "imgpng");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myImg));
        bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
        bos.flush();
        bos.close();
        return myImg;
    }
}
